<script setup>
import { ref, onMounted } from 'vue'
import { useAuthStore } from '../../store/auth'
import { getUser, updateUser, changePassword } from '../../api/user'
import { ElMessage } from 'element-plus'

const auth = useAuthStore()
const form = ref({})
const loading = ref(false)
const pwdDialog = ref(false)
const pwdForm = ref({ oldPassword: '', newPassword: '' })

const fetchData = async () => {
  loading.value = true
  try {
    const data = await getUser(auth.currentId)
    form.value = data || {}
  } finally { loading.value = false }
}

const submit = async () => {
  loading.value = true
  try {
    await updateUser(auth.currentId, form.value)
    ElMessage.success('更新成功')
  } finally { loading.value = false }
}

const submitPwd = async () => {
  loading.value = true
  try {
    await changePassword({ userId: auth.currentId, ...pwdForm.value })
    ElMessage.success('密码修改成功')
    pwdDialog.value = false
    pwdForm.value = { oldPassword: '', newPassword: '' }
  } finally { loading.value = false }
}

onMounted(fetchData)
</script>

<template>
  <el-card>
    <h3>个人中心</h3>
    <el-form :model="form" label-width="120px" style="max-width:600px">
      <el-form-item label="用户名">
        <el-input v-model="form.username" />
      </el-form-item>
      <el-form-item label="姓名">
        <el-input v-model="form.name" />
      </el-form-item>
      <el-form-item label="性别">
        <el-select v-model="form.gender" placeholder="选择">
          <el-option label="男" value="男" />
          <el-option label="女" value="女" />
        </el-select>
      </el-form-item>
      <el-form-item label="年龄">
        <el-input v-model.number="form.age" type="number" />
      </el-form-item>
      <el-form-item label="手机号">
        <el-input v-model="form.phone" />
      </el-form-item>
      <el-form-item label="身份证">
        <el-input v-model="form.idCard" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" :loading="loading" @click="submit">保存</el-button>
        <el-button @click="pwdDialog=true">修改密码</el-button>
      </el-form-item>
    </el-form>
  </el-card>

  <el-dialog v-model="pwdDialog" title="修改密码" width="420px">
    <el-form :model="pwdForm" label-width="100px">
      <el-form-item label="旧密码"><el-input v-model="pwdForm.oldPassword" type="password" /></el-form-item>
      <el-form-item label="新密码"><el-input v-model="pwdForm.newPassword" type="password" /></el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="pwdDialog=false">取消</el-button>
      <el-button type="primary" :loading="loading" @click="submitPwd">提交</el-button>
    </template>
  </el-dialog>
</template>